package com.estasenposse.tdam.ui.adapter;

import java.io.InputStream;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.estasenposse.tdam.services.ConectivityStatus;

public class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
	private ImageView bmImage;
	private ProgressBar pgLoading;
	private Context context;

	public ImageDownloader(ImageView bmImage, ProgressBar loading,
			Context context) {
		this.bmImage = bmImage;
		this.pgLoading = loading;
		if (context != null) {
			this.context = context;
		}

	}

	@Override
	protected void onPreExecute() {
		pgLoading.setVisibility(View.VISIBLE);
	}

	protected Bitmap doInBackground(String... urls) {
		ConectivityStatus cs = new ConectivityStatus(context);
		Bitmap mIcon11 = null;
		
		if (cs.isConected()) {
			String urldisplay = urls[0];
			 if(urldisplay.contains(" ")){
				 urldisplay = urldisplay.replace(" ", "%20");
				 Log.i("IMAGEN: (Anterior)", urldisplay);
			    }

			try {
				InputStream in = new java.net.URL(urldisplay).openStream();
				mIcon11 = BitmapFactory.decodeStream(in);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return mIcon11;
	}

	@Override
	protected void onPostExecute(Bitmap result) {
		bmImage.setImageBitmap(result);
		//Is not correct do this here.
		pgLoading.setVisibility(View.GONE);
		bmImage.setVisibility(View.VISIBLE);
	}
}